# author: axin
# date: 2021/4/21 20:31
# description:
from django.conf import settings
from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ModelViewSet  # ModelViewSet实现了增删改查等五个功能
from rest_framework.response import Response

from goods.models import SKUImage, SKU
from meiduo_admin.serialziers.images import ImagesSerialziers, SKUSerializer
from meiduo_admin.utils import PageNum
from fdfs_client.client import Fdfs_client


class ImageView(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = ImagesSerialziers
    pagination_class = PageNum

    # 指定权限
    permission_classes = [IsAdminUser]

    def simple(self, request):
        """获取SKU商品信息"""
        # 查询所有SKU商品
        skus = SKU.objects.all()
        # 序列化返回
        ser = SKUSerializer(skus, many=True)
        return Response(ser.data)

    def create(self, request, *args, **kwargs):
        # 获取前端数据
        data = request.data
        # 验证数据
        ser = self.get_serializer(data=data)
        ser.is_valid()
        # # 建立fastdfs的客户端
        # client = Fdfs_client(settings.FASTDFS_PATH)
        # file = request.FILES.get('image')
        # # 上传图片
        # res = client.upload_by_buffer(file.read())
        # # 判断是够上传成功
        # if res['Status'] != 'Upload successed.':
        #     return Response({'error': '图片上传失败'})
        # # 保存图片表
        # img = SKUImage.objects.create(sku=ser.validated_data['sku'], image=res['Remote file_id'])
        ser.save()
        # 返回保存后的图片数据
        return Response(ser.data, status=201)
